package middleware

import (
	"bytes"
	"illuminant/logger"
	"illuminant/util"
	"io/ioutil"
	"strings"

	jwt "github.com/appleboy/gin-jwt/v2"
	"github.com/gin-gonic/gin"
)

type HasuraWhere struct {
	GQLKey        string
	JWTKey        string
	CheckGQLFuncs []string
}

func NewHasuraWhereMiddleware(jwtKey, gqlKey string, gqlFuncs []string) gin.HandlerFunc {
	hw := &HasuraWhere{
		GQLKey:        gqlKey,
		JWTKey:        jwtKey,
		CheckGQLFuncs: gqlFuncs,
	}

	return func(c *gin.Context) {
		hw.AddWhereCondition(c)
	}
}

func (hw *HasuraWhere) AddWhereCondition(c *gin.Context) {
	lg := logger.GetLogger()
	claims := jwt.ExtractClaims(c)

	path := c.Request.URL.Path

	if strings.Index(path, "/api/v1/graphql") < 0 {
		return
	}

	// graphql api
	body, err := c.GetRawData()
	if err != nil {
		lg.Err(err).Msg("HasuraWhere middleware: AddWhereCondition")
		return
	}
	newBody, err := util.AddWhereCondition(body, hw.GQLKey, claims[hw.JWTKey].(string), hw.CheckGQLFuncs)
	if err != nil {
		lg.Err(err).Msg("HasuraWhere middleware: AddWhereCondition")
		return
	}

	c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(newBody))
	c.Request.ContentLength = int64(len(newBody))
}
